<template>
  <div class="department-container">
    <div class="app-container">
      <!-- 具体页面结构 -->
      <page-tools>
        <template #left>
          <span>总的记录数:xx条</span>
        </template>
        <template #right>
          <el-button v-allow="'import_excel'" type="warning">导入excel</el-button>
          <el-button v-allow="'export_excel'" type="danger" @click="exportToExcel">导出excel</el-button>
          <el-button v-allow="'add'" type="primary" @click="hAdd">新增员工</el-button>
        </template>
      </page-tools>
      <el-card style="margin-top: 10px;">
        <el-table border :data="list" :default-sort="{prop: 'timeOfEntry', order: 'descending'}">
          <el-table-column label="序号" type="index" />
          <el-table-column label="姓名" prop="username" />
          <el-table-column label="头像">
            <template #default="{row}">
              <img :src="row.staffPhoto" alt="" style="width: 80px;height: 80px;">
            </template>
          </el-table-column>
          <el-table-column label="工号" prop="workNumber" />
          <el-table-column label="聘用形式">
            <template #default="{row}">
              {{ fromatHrieType(row.formOfEmployment) }}
            </template>
          </el-table-column>
          <el-table-column label="部门" prop="departmentName" />
          <el-table-column label="入职时间" prop="timeOfEntry" sortable />
          <el-table-column label="操作" width="280">
            <template #default="{row}">
              <el-button
                type="text"
                size="small"
                @click="$router.push('/employees/detail?id='+row.id)"
              >查看</el-button>
              <el-button type="text" size="small" @click="hRoles(row.id)">分配角色</el-button>
              <el-button type="text" size="small" @click="hdel(row.id)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页组件 -->
        <el-row type="flex" justify="center" align="middle" style="height: 60px">
          <el-pagination
            :current-page="page"
            :page-sizes="[1, 3, 5, 8]"
            :page-size="size"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </el-row>
      </el-card>
      <el-dialog title="新增员工" :visible.sync="showDialog" @close="hclose">
        <addor-edit ref="myEmp" @success="hsuccess" />
      </el-dialog>
      <!-- 分配角色 -->
      <el-dialog :visible.sync="showDialogRole">
        <assign-role v-if="showDialogRole" ref="myRole" :user-id="userId" @close="showDialogRole=false" @success="showDialogRole=false" />
      </el-dialog>
    </div>
  </div>
</template>

<script>
import AssignRole from './assignRole'
// 导入对话框内容
import addorEdit from './empDialog.vue'
import { getEmployeeList, delEmployeeUser } from '@/api/employees'
import employeesEnum from '@/constant/employees'
// const hireType = {}
// employeesEnum.hireType.forEach(item => {
//   hireType[item.id] = item.value
// })
const hireType = employeesEnum.hireType.reduce((sum, item) => {
  sum[item.id] = sum.value
  return sum
}, {})
export default {
  name: 'EmployeesPage',
  components: {
    addorEdit,
    AssignRole
  },
  data() {
    return {
      list: [],
      page: 1,
      size: 5,
      total: 0,
      showDialog: false,
      showDialogRole: false,
      userId: ''
    }
  },
  created() {
    this.loadArchives()
  },
  methods: {
    // Aclose() {
    //   this.$refs.myRole.resetForm()
    // },
    // 分配角色
    hRoles(id) {
      this.userId = id
      this.showDialogRole = true
    },
    exportToExcel() {
      const { tHeader, result } = this.formatToExcel(this.list)
      console.log(tHeader, 'tHeader')
      console.log(result, 'result')
      import('@/vendor/Export2Excel').then(excel => {
        excel.export_json_to_excel({
          header: tHeader,
          data: result,
          filename: '好人一身平安',
          autoWidth: true,
          bookType: 'xlsx'
        })
        this.downloadLoading = false
      })
    },
    // 格式化excel的数据格式
    formatToExcel(list) {
      //    中引文的映射对象
      const mapInfo = {
        'id': '编号',
        'password': '密码',
        'mobile': '手机号',
        'username': '姓名',
        'timeOfEntry': '入职日期',
        'formOfEmployment': '聘用形式',
        'correctionTime': '转正日期',
        'workNumber': '工号',
        'departmentName': '部门',
        'staffPhoto': '头像地址'
      }

      // tHeader = ['编号','密码','手机号','姓名','入职日期',.......]
      // 1 生成表头
      // tHeader  ---> ['转正日期', '部门', '聘用形式', '编号', '手机号', '密码', '头像地址', '入职日期', '姓名', '工号']
      const one = list[0]
      if (!one) return
      const tHeader = Object.keys(one).map(en_key => {
        return mapInfo[en_key]
      })
      // 2 生成表的内容data
      const result = list.map(item => {
        return Object.values(item)
      })
      return { tHeader, result }
    },
    // 点击重置表单
    hclose() {
      this.$refs.myEmp.resetForm()
    },
    // 点击删除
    hdel(id) {
      this.$confirm('您确定删除吗', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async() => {
        await delEmployeeUser(id)
        if (this.list.lenght === 1) {
          this.page--
          if (this.page < 0) {
            this.page = 1
          }
        }
        this.loadArchives()
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    // 确定关闭弹层
    hsuccess() {
      this.showDialog = false
      this.total++
      this.page = Math.ceil(this.total / this.size)
      this.loadArchives()
    },
    // 添加打开弹框
    hAdd() {
      this.showDialog = true
    },
    // 格式化聘用形式数据
    fromatHrieType(value) {
      // const obj = employeesEnum.hireType.find(item => {
      //   return item.id === Number(value)
      // })
      // return obj ? obj.value : '未知'
      return hireType[value] || '未知'
    },
    handleSizeChange(val) {
      this.page = 1
      this.size = val
      this.loadArchives()
    },
    handleCurrentChange(val) {
      this.page = val
      this.loadArchives()
    },
    async loadArchives() {
      try {
        const res = await getEmployeeList({ page: this.page, size: this.size })
        this.list = res.data.rows
        this.total = res.data.total
      } catch (error) {
        console.log(error)
      }
    }
  }
}

</script>

<style>
</style>
